package com.inspirationandgenius.welcome;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;

import com.inspirationandgenius.media.StreamingMedia;
import com.inspirationandgenius.media.StreamingMediaPlayer;
import com.lifeofdata.inspirationandgenius.R;

public class Radio extends ListActivity {

	
	private ImageButton playButton;
	
	private ProgressBar progressBar;
	
	private TextView textStreamed;
	
	
	private boolean isPlaying=true;
	
	private StreamingMediaPlayer audioStreamer;
	private StreamingMedia Streamer;
	
	// Progress Dialog
    private ProgressDialog pDialog;
 
    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();
 
    ArrayList<HashMap<String, String>> radiosList;
 
    // url to get all products list
//    local
   //private static String url_all_radio = "http://192.168.1.8/test/get_all_radios.php";
//	Remote
   private static String url_all_radio = "http://www.lifeofdata.com/inspirationandgenius/get_all_radios.php";
   private static String url_action_radio = "http://www.lifeofdata.com/inspirationandgenius/iglike.php";
    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_RADIO = "radio";
    private static final String TAG_ID = "id";
    private static final String TAG_NAME = "name";
    private static final String TAG_FOUNDER = "founder";
    private static final String TAG_URL = "url";
    private static final String TAG_IDUSER = "iduser";
    private static final String TAG_NBSAD = "nbsad";
    private static final String TAG_NBLIKE = "nblike";
    private static final String TAG_ACTION = "action";
    private String rname;
    private String foriguser;
   
    NotificationManager RaidionotificationManager ;
    // products JSONArray
    JSONArray radio = null;
	
    @Override
	public void onCreate(Bundle icicle) {
    	
        super.onCreate(icicle);
        
        if(this.getIntent().getExtras()==null)
        {
        	Intent h = new Intent(this, ControlTower.class);
        	startActivity(h);
        	finish();
        }
        
        foriguser=this.getIntent().getExtras().getString("igcnuserid");
        
        setContentView(R.layout.radio);
        
        TextView textStreamed = (TextView) findViewById(R.id.text_kb_streamed);
        textStreamed.setText("Hi "+this.getIntent().getExtras().getString("loginn")+" ! You are on Ig radio :) ");
                
        RaidionotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        RaidionotificationManager.cancelAll();
        // Hashmap for ListView
        radiosList = new ArrayList<HashMap<String, String>>();
        
        // Loading products in Background Thread
        new LoadAllRadios().execute();
 
        // Get listview
        final ListView lv = getListView();
 
        // on seleting single product
        // launching Edit Product Screen
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
 
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
            	
           final String url = ((TextView) view.findViewById(R.id.url)).getText()
                        .toString();
            rname = ((TextView) view.findViewById(R.id.name)).getText()
                   .toString();
           
            
           Toast.makeText(getApplicationContext(), url+" "+rname, Toast.LENGTH_LONG).show();
           		
        	   initControls(url);
            }
        });
        
        
    } 
    
    
    // Response from Edit Product Activity
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // if result code 100
        if (resultCode == 100) {
            // if result code 100 is received
            // means user edited/deleted product
            // reload this screen again
            Intent intent = getIntent();
            finish();
            startActivity(intent);
        }
    }
    
    private void initControls(final String url) {
    	textStreamed = (TextView) findViewById(R.id.text_kb_streamed);
    	//textStreamed.setSelected(true);
				startStreamingAudio(url);

		playButton = (ImageButton) findViewById(R.id.button_play);
		playButton.setEnabled(false);
		playButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				if (audioStreamer.getMediaPlayer().isPlaying()) {
					audioStreamer.getMediaPlayer().pause();
					playButton.setImageResource(R.drawable.av_play_over_video);
				} else {
					audioStreamer.getMediaPlayer().start();
					audioStreamer.startPlayProgressUpdater();
					playButton.setImageResource(R.drawable.av_pause_over_video);
				}
				isPlaying = !isPlaying;
        }});
    }
    
 
    private void startStreamingAudio(final String url) {
    	try { 
    		final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar);
    		progressBar.setMax(100);
    		if ( audioStreamer != null) {
    			audioStreamer.interrupt();
    		}
    		audioStreamer = new StreamingMediaPlayer(this,textStreamed, playButton, progressBar , rname);
    		audioStreamer.startStreaming(url,5208, 216);
    		
    		
    		Notification rnf = new Notification(R.drawable.inpge, rname , System.currentTimeMillis());
    		rnf.contentView = new RemoteViews(getPackageName(),R.layout.activity_radioinfo);
    		Intent rintent = new Intent(this, Radioinfo.class);
    		rintent.putExtra("textradio", audioStreamer.getRme()+"");
    		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, rintent, 0);
    		rnf.contentIntent = pendingIntent;
    		
    		 rintent = new Intent(this, Radio.class);
    		 rnf.deleteIntent = PendingIntent.getActivity(this, 0, rintent, 0);
   
    		RaidionotificationManager.notify(-1, rnf);
    	} catch (IOException e) {
	    	Log.e(getClass().getName(), "Error starting to stream audio.", e);            		
    	}
    	    	
    }
    
    /**
     * Background Async Task to Load all product by making HTTP Request
     * */
    class LoadAllRadios extends AsyncTask<String, String, String> {
    	
        /**
         * Before starting background thread Show Progress Dialog
         * */
    	
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(Radio.this);
            pDialog.setMessage("Loading radio. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All products from url
         * */
        protected String doInBackground(String... args) {
           
        	radiosList = new ArrayList<HashMap<String, String>>();
        	
        	 List<NameValuePair> params = new ArrayList<NameValuePair>();
             params.add(new BasicNameValuePair("iduser", foriguser));
             
            JSONObject json = jParser.makeHttpRequest(url_all_radio, "POST", params);// makeHttpRequest(url_all_radio, "GET", params);

            if(json==null)
            {
            	HashMap<String, String> map = new HashMap<String, String>();
            	
            	map.put(TAG_ID, "");
            	map.put(TAG_NAME, "");
            	map.put(TAG_FOUNDER, "No radio found or Connection to the server failed check your internet connection your internet connection may be slow");
            	map.put(TAG_URL,"");
            	map.put(TAG_ACTION, "");
                map.put(TAG_IDUSER, "");
                map.put(TAG_NBLIKE, "");
                map.put(TAG_NBSAD, "");
            	
            	radiosList.add(map);
            	
            	Toast.makeText(getApplicationContext(), "Sorry ! Connection to the server failed", Toast.LENGTH_LONG).show();
            	return null;
            }
            	
            // Check your log cat for JSON reponse
            Log.d("All Radio: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    radio = json.getJSONArray(TAG_RADIO);

                    // looping through All Products
                    for (int i = 0; i < radio.length(); i++) {
                        JSONObject c = radio.getJSONObject(i);

                        // Storing each json item in variable
                        String id = c.getString(TAG_ID);
                        String name = c.getString(TAG_NAME);
                        String founder = c.getString(TAG_FOUNDER);
                        String url = c.getString(TAG_URL);
                        String iduser = c.getString(TAG_IDUSER);
                        String action = c.getString(TAG_ACTION);
                        String nblike = c.getString(TAG_NBLIKE);
                        String nbsad = c.getString(TAG_NBSAD);

                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        map.put(TAG_ID, id);
                        map.put(TAG_NAME, name);
                        map.put(TAG_FOUNDER, founder);
                        map.put(TAG_URL, url);
                        map.put(TAG_ACTION, action);
                        map.put(TAG_IDUSER, iduser);
                        map.put(TAG_NBLIKE, nblike);
                        map.put(TAG_NBSAD, nbsad);

                        // adding HashList to ArrayList
                        radiosList.add(map);
                    }
                }
                else
                {
                	HashMap<String, String> map = new HashMap<String, String>();
                	
                	map.put(TAG_ID, "");
                	map.put(TAG_NAME, "");
                	map.put(TAG_FOUNDER, "No radio found ");
                	map.put(TAG_URL,"");
                	map.put(TAG_ACTION, "");
                    map.put(TAG_IDUSER, "");
                    map.put(TAG_NBLIKE, "");
                    map.put(TAG_NBSAD, "");
                	
                	radiosList.add(map);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            
            
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    MyradioAdapteur adapter = new MyradioAdapteur(getApplicationContext(),radiosList);
                    setListAdapter(adapter);
                	}
            });

        }
        
        
        
        
}
    
    public class MyradioAdapteur extends BaseAdapter{
    	
    	private String pposition;
    	private class MyradioTag
    	{
    		TextView founder;
    		TextView name;
    		TextView id;
    		TextView url;
    		TextView ilike;
    		TextView isad;
    		Button blike;
    		Button bsad;
    		Button bcom;
    	}
    	
    	ArrayList<HashMap<String, String>> data;
    	LayoutInflater layoutInflater;
    	
    	
		public MyradioAdapteur(Context context, ArrayList<HashMap<String, String>> data) {
			this.data = data;
			this.layoutInflater = LayoutInflater.from(context);
		}
		
		public int getCount() {
			// TODO Auto-generated method stub
			return data.size();
		}
		public Object getItem(int position) {
			return data.get(position);
		}
		public long getItemId(int position) {
			return position;
		}
		
		@Override
		public int getItemViewType(int position) {
			return position & 1;
		}
		
		@Override
		public int getViewTypeCount() {
			return 2;
		}
		public View getView(int position, View convertView, ViewGroup parent) {
			final MyradioTag holder;
			
			if(convertView==null)
			{
				switch (getItemViewType(position)) {
				case 0: convertView = layoutInflater.inflate(R.layout.list_radio_item, null);break;
				case 1: convertView = layoutInflater.inflate(R.layout.list_radio_itemb, null);break;
				}
				
				holder = new MyradioTag();
				
				holder.founder = (TextView)convertView.findViewById(R.id.founder);
				holder.name = (TextView)convertView.findViewById(R.id.name);
				holder.url = (TextView)convertView.findViewById(R.id.url);
				holder.id = (TextView)convertView.findViewById(R.id.id);
				holder.blike = (Button)convertView.findViewById(R.id.blike);
				holder.bsad = (Button)convertView.findViewById(R.id.bsad);
				holder.bcom = (Button)convertView.findViewById(R.id.bcom);
				holder.ilike = (TextView)convertView.findViewById(R.id.ilike);
				holder.isad = (TextView)convertView.findViewById(R.id.isad);
				convertView.setTag(holder);
			}
			else
			{
				holder = (MyradioTag)convertView.getTag();
			}
			
			holder.founder.setText(data.get(position).get(TAG_FOUNDER));
			holder.name.setText(data.get(position).get(TAG_NAME));
			holder.url.setText(data.get(position).get(TAG_URL));
			holder.id.setText(data.get(position).get(TAG_ID));
			
			if(data.get(position).get(TAG_IDUSER).trim().equalsIgnoreCase(foriguser.trim()))
			{
				if(data.get(position).get(TAG_ACTION).trim().equalsIgnoreCase("1"))
				{
					holder.blike.setBackgroundResource(R.drawable.happygreen);
					holder.blike.setEnabled(false);
					holder.bsad.setEnabled(false);
					
					if(Integer.parseInt(data.get(position).get(TAG_NBLIKE)) == 1 )
						holder.ilike.setText("You ");
					else
						holder.ilike.setText("You and "+ (Integer.parseInt(data.get(position).get(TAG_NBLIKE)) - 1 ));
					
					
				}
				
				else if(data.get(position).get(TAG_ACTION).trim().equalsIgnoreCase("2"))
				{
					holder.bsad.setBackgroundResource(R.drawable.sadgreen);
					holder.blike.setEnabled(false);
					holder.bsad.setEnabled(false);
					
					if(Integer.parseInt(data.get(position).get(TAG_NBSAD)) == 1)
						holder.isad.setText(" You");
					else
					holder.isad.setText("You and "+(Integer.parseInt(data.get(position).get(TAG_NBSAD)) - 1));
					
					
				}
				
				else
				{
					holder.blike.setBackgroundResource(R.drawable.happy);
					holder.bsad.setBackgroundResource(R.drawable.sad);
					holder.blike.setEnabled(true);
					holder.bsad.setEnabled(true);
				}
				
			}
			else
			{
					holder.isad.setText(data.get(position).get(TAG_NBSAD));
					holder.ilike.setText(data.get(position).get(TAG_NBLIKE));
					holder.blike.setBackgroundResource(R.drawable.happy);
					holder.bsad.setBackgroundResource(R.drawable.sad);
					holder.blike.setEnabled(true);
					holder.bsad.setEnabled(true);
				
			}
			
			holder.blike.setTag(position);
			holder.bsad.setTag(position);
			holder.bcom.setTag(position);
			holder.blike.setOnClickListener(new View.OnClickListener() {
				
				public void onClick(View v) {
					LikeAction likeAction = new LikeAction(data.get((Integer)v.getTag()).get(TAG_ID),"1",foriguser.toString());
					likeAction.execute();
						holder.blike.setBackgroundResource(R.drawable.happygreen);
						holder.blike.setEnabled(false);
						holder.bsad.setEnabled(false);
						String value = (String) holder.ilike.getText();
						if(Integer.parseInt(value.trim())==0)
							holder.ilike.setText("You ");
						else
							holder.ilike.setText("You and "+ (Integer.parseInt(value.trim())));
				}
			});
			holder.bsad.setOnClickListener(new View.OnClickListener() {
				
				public void onClick(View v) {
					
					LikeAction likeAction = new LikeAction(data.get((Integer)v.getTag()).get(TAG_ID),"2",foriguser.toString());
					likeAction.execute();
						holder.bsad.setBackgroundResource(R.drawable.sadgreen);
						holder.blike.setEnabled(false);
						holder.bsad.setEnabled(false);
						String value1 = (String) holder.isad.getText();
						if(Integer.parseInt(value1.trim())==0)
							holder.isad.setText(" You");
						else
							holder.isad.setText("You and "+(Integer.parseInt(value1.trim())));
				}
			});
			holder.bcom.setOnClickListener(new View.OnClickListener() {
				
				public void onClick(View v) {
					Toast.makeText(getApplicationContext(), data.get((Integer)v.getTag()).get(TAG_URL), Toast.LENGTH_LONG).show();
				}
			});
			return convertView;
		}
		 	
		class LikeAction extends AsyncTask<String, String, String> {
			private String p,ac,ui;
			
			
	         public LikeAction(String p, String ac, String ui) {
				this.p = p;
				this.ac = ac;
				this.ui = ui;
			}


			protected String doInBackground(String... args) {
	                        // Building Parameters
	             List<NameValuePair> params = new ArrayList<NameValuePair>();
	             params.add(new BasicNameValuePair("iduser", ui));
	             params.add(new BasicNameValuePair("idradio", p));
	             params.add(new BasicNameValuePair("action", ac));
	             // getting JSON Object
	             // Note that create product url accepts POST method
	             JSONObject json = jParser.makeHttpRequest(url_action_radio,"POST", params);
	             return null;
	         }
	     }
    	
    }
		

}




